// pages/mine/mine.js
const app = getApp(),
    globalData = app.globalData,
    api = require('../../api/index'),
    http = require('../../utils/http'),
    utils = require('../../utils/util');
    
Page({

    /**
     * 页面的初始数据
     */
    data: {
        phoneCode: 1,
        phoneType: false,
        phoneObjiv: "",
        phoneObjencryptedData: "",
        phoneObjcode: "",
        informImg: globalData.pictureRouting + 'myBackgroundpicture.png',
        feiImg: globalData.pictureRouting + 'consumption_icon.png',
        tiImg: globalData.pictureRouting + 'MoneyBackgroundIcon.png',
        daifukImg: globalData.pictureRouting + 'daifukuan_icon.png',
        daifahuoImg: globalData.pictureRouting + 'daifahuo_icon.png',
        daishouhuoImg: globalData.pictureRouting + 'daishouhuo_icon.png',
        yiwanchengImg: globalData.pictureRouting + 'yiwancheng_icon.png',
        tuiShouImg: globalData.pictureRouting + 'tuiguanhuoshouhou_icon.png',
        kucunImg: globalData.pictureRouting + 'wodekucun_icon.png',
        zitiIMg: globalData.pictureRouting + 'wodeziti_icon.png',
        buhuoImg: globalData.pictureRouting + 'wodebuhuo_icon.png',
        tuanduiguanImg: globalData.pictureRouting + 'tuanduiguanli_icon.png',
        kanjiaImg: globalData.pictureRouting + 'wodekanjia_icon.png',
        tuangouImg: globalData.pictureRouting + 'wodetuandui_icon.png',
        ypuhuiqImg: globalData.pictureRouting + 'youhuiquan_icon.png',
        kefuImg: globalData.pictureRouting + 'kehuzhongx_icon.png',
        gunayuImg: globalData.pictureRouting + 'guanyuwomen_icon.png',
        tuichuImg: globalData.pictureRouting + 'tuicudenglu_icon.png',
        loading: false,
        toast: {
            visible: false,
            text: ''
        },
        userInfo: {},
        agentInfo: {}, // 是否代理商的信息
        agentLoading: false,
        imageBaseUri: globalData.isDev ? 'http://47.114.5.153:8082' : globalData.imageBaseUri,
        status: 0,
        canIUseGetUserProfile: false,
        name: '',
        headPortrait: '',
        showMask: false,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

        this.setData({
            phoneCode: wx.getStorageSync("phonecode")
        })


        let phone=wx.getStorageSync('phonecode')
        if (phone == "" || null) {
            this.setData({
                phoneCode: phone
            })
        } else {
            this.setData({
                phoneCode: 1
            })
        }

        // console.log(this.data.userInfo, 'userInfo')
        // if (wx.getUserProfile) {

        //     console.log('111')
        //     this.setData({
        //         canIUseGetUserProfile: true
        //     })
        // } else {
        //     console.log('222')

        // }
    },

    onPullDownRefresh: function () {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.reload()
    },
        // 上传 用户信息
        uploadUserInfo() {
            let that = this
            if (that.data.name == '') return wx.showToast({
                title: '请填写昵称',
                icon: 'none'
            })
            if (that.data.headPortrait == '') return wx.showToast({
                title: '请选择头像',
                icon: 'none'
            })
            let obj = {
                nickname: that.data.name,
                province: '',
                sex: 1,
                city: '',
                country: '',
                headimgurl: that.data.headPortrait,
                unionid: '',
                code: '',
                invitationId:wx.getStorageSync('superiorsID')||''
            }
            console.log(obj);

            wx.login({
                success: res => {
                    console.log('wx.login', res)
                    this.setData({
                        loading: true
                    })
                    try {
                        api.base.wxOnLogin(Object.assign(obj, {
                            code: res.code
                        })).then(res => {
                            console.log(res, '登录结果')
                            let token = res.data.ResData.AccessToken || '',
                                userinfo = res.data.ResData || {};
                                that.setData({
                                    showMask: false
                                })
                            // this.setData({
                            //   userInfo: res.data.ResData || {},
                            //   loading: false
                            // })

                            //token
                            wx.setStorageSync('token', token);
                            // app.globalData.authToken = token;

                            //存放用户信息
                            wx.setStorageSync('userinfo', userinfo);
                            app.globalData.userInfo = userinfo;

                            // 存放sessionId
                            wx.setStorageSync('ssId', userinfo.WxSessionId);
                            app.globalData.ssId = userinfo.WxSessionId;
                            that.setData({
                                phoneType: true
                            })
                            this.reload();
                        })
                    } catch (e) {
                        this.setData({
                            loading: false
                        })
                    }
                }
            })
        },
    
    
    
        // 获取头像
        onChooseAvatar(e) {
            let that = this
            that.setData({
                headPortrait: e.detail.avatarUrl
            })
            wx.uploadFile({
                url: globalData.baseUrl+'api/common/upload',
                filePath: e.detail.avatarUrl,
                name: 'file',
                success: function (res) {
                    console.log(res)
                    console.log(JSON.parse(res.data).ResData)
                    that.setData({
                        headPortrait: JSON.parse(res.data).ResData.fullurl
                    })
                    console.log(that.data.headPortrait,'xxxxxxxxxxxxxxxxxxxxxx')
                }
            })
        },
    
        // 获取名称
        getName(e) {
            console.log(e)
            this.setData({
                name: e.detail.value
            })
        },
    
    
    
        maskBtn() {
            this.setData({
                showMask: false
            })
            // 关闭后处理问题
        },
    reload() {
        this.setData({
            userInfo: wx.getStorageSync('userinfo') || {},
            status: 2
        })

        console.log(this.data.userInfo, 'userInfo')
        if (this.data.userInfo.AccessToken) {
            this.getBalance();
            this.getUser();
            this.getBenefits();
        }
        if (this.data.agentInfo && this.data.agentInfo.MemberGradeId) {
            this.getBenefits();
        }
    },

    toMyIncome() {
        wx.navigateTo({
            url: '/pages/mine/myIncome/myIncome',
        })
    },

    toCoupon() {
        wx.navigateTo({
            url: '/pages/mine/coupon/moreList/moreList',
        })
    },

    async toMyOrder() {
        // 订阅下级支付成功通知
        await utils.subscribe('cTHEhOYPqcC693tSzZ_1MTbixtbKbXmrL2aGhzMrviw');

        wx.navigateTo({
            url: '/pages/mine/myOrder/myOrder',
        })
    },

    toApply() {
        wx.navigateTo({
            url: `/pages/mine/myStock/myStock?tab=1`,
        })
        // wx.navigateTo({
        //   url: `/pages/product/detail/detail?id=2008291227289650512`,
        // })
        // wx.switchTab({
        //   url: '/pages/index/index',
        // })
    },
    //关于我们
    about() {
        wx.navigateTo({
            url: '/pages/mine/about/about',
        })
    },
    toAddress() {
        wx.navigateTo({
            url: '/pages/product/address/address',
        })
    },

    toCart() {
        wx.switchTab({
            url: '/pages/car/car',
        })
    },

    toAgreement() {
        wx.navigateTo({
            url: '/pages/mine/agreements/agreements',
        })
    },

    getUserProfile() {
        // console.log(globalData.baseUrl)
        let that = this;
        this.setData({
            showMask: true
        })
        return false;
        // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
        // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
        wx.getUserProfile({
            desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: (res) => {
                console.log(res, '登录profile返回的res')
                let user = res.userInfo;
                that.setData({
                    phoneObjiv: res.iv,
                    phoneObjencryptedData: res.encryptedData
                })
                
                console.log(that.data.phoneObjiv, that.data.phoneObjencryptedData, "465656565");
                let obj = {
                    nickname: user.nickName.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "*"),
                    province: user.province,
                    sex: user.gender,
                    city: user.city,
                    country: user.country,
                    headimgurl: user.avatarUrl,
                    unionid: '',
                    code: res.code || '',
                    invitationId:wx.getStorageSync('superiorsID')||''
                }
                console.log(obj);

                wx.login({
                    success: res => {
                        console.log('wx.login', res)
                        this.setData({
                            loading: true
                        })
                        try {
                            api.base.wxOnLogin(Object.assign(obj, {
                                code: res.code
                            })).then(res => {
                                console.log(res, '登录结果')
                                let token = res.data.ResData.AccessToken || '',
                                    userinfo = res.data.ResData || {};

                                // this.setData({
                                //   userInfo: res.data.ResData || {},
                                //   loading: false
                                // })

                                //token
                                wx.setStorageSync('token', token);
                                // app.globalData.authToken = token;

                                //存放用户信息
                                wx.setStorageSync('userinfo', userinfo);
                                app.globalData.userInfo = userinfo;

                                // 存放sessionId
                                wx.setStorageSync('ssId', userinfo.WxSessionId);
                                app.globalData.ssId = userinfo.WxSessionId;
                                that.setData({
                                    phoneType: true
                                })
                                this.reload();
                            })
                        } catch (e) {
                            this.setData({
                                loading: false
                            })
                        }
                    }
                })
            },
            fail(e){
                console.error("登录失败",e)
            }
        })
    },

    async getUserInfo(res) {
        console.log(res, '获取用户信息1')
        // wx.navigateTo({
        //   url: '/pages/login/login',
        // })
        if (res.detail) {
            let user = res.detail.userInfo;
            let obj = {
                nickname: user.nickName.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "*"),
                province: user.province,
                sex: user.gender,
                city: user.city,
                country: user.country,
                headimgurl: user.avatarUrl,
                unionid: '',
            }

            wx.login({
                success: res => {
                    console.log('wx.login', res)
                    this.setData({
                        loading: true
                    })
                    try {
                        api.base.wxOnLogin(Object.assign(obj, {
                            code: res.code
                        })).then(res => {
                            console.log(res, '登录结果')
                            let token = res.data.ResData.AccessToken || '',
                                userinfo = res.data.ResData || {};

                            this.setData({
                                userInfo: res.data.ResData || {},
                                loading: false
                            })

                            //token
                            wx.setStorageSync('token', token);
                            // app.globalData.authToken = token;

                            //存放用户信息
                            wx.setStorageSync('userinfo', userinfo);
                            app.globalData.userInfo = userinfo;

                            // 存放sessionId
                            wx.setStorageSync('ssId', userinfo.WxSessionId);
                            app.globalData.ssId = userinfo.WxSessionId;
                            this.reload();
                        })
                    } catch (e) {
                        this.setData({
                            loading: false
                        })
                    }
                }
            })
        }

    },

    copy(e) {
        utils.copy(e.currentTarget.dataset.id)
    },

    logout() {
        wx.clearStorageSync();
        this.setData({
            toast: {
                visible: true,
                text: '退出登录成功'
            },
            userInfo: {},
            agentInfo: {}
        })
        globalData.authToken = ''
        // wx.switchTab({
        //   url: '/pages/index/index',
        // })
    },

    // 获取我的收益
    async getBenefits() {
        try {
            let res = await api.balance.getMyBenefits(),
                data = res.data.ResData || {};
            this.setData({
                status: 2,
                pageData: data
            })
            console.log(res, '我的收益')
        } catch (e) {
            this.setData({
                status: 1
            })
            console.log(e, '获取我的收益失败')
        }
    },

    // 获取我的可提现金额
    async getBalance() {
        try {
            let res = await api.balance.getMyBalance(),
                data = res.data.ResData || 0;
            this.setData({
                status: 2,
                balance: data
            })
            console.log(res, '可提现金额')
        } catch (e) {
            this.setData({
                status: 1
            })
            console.log(e, '获取可提现金额失败')
        }
    },

    // 登录后获取用户等级信息
    async getUser() {
        let that = this
        this.setData({
            agentLoading: true
        })
        try {
            let res = await api.user.getUser(),
                data = res.data.ResData || {};
            console.log(res);
            this.setData({
                agentInfo: data,
                agentLoading: false,
                status: 2
            })
            wx.setStorageSync('agentInfo', data)
            console.log(res, '获取用户等级信息')

        } catch (e) {
            console.log(e, '获取用户等级信息失败')
            this.setData({
                agentLoading: false,
                toast: {
                    visible: true,
                    text: e.data.ErrMsg
                },
                status: 1
            })
        }
    },
    gotoScan() {
        wx.navigateTo({
            url: '/pages/scan/scan'
        });
    },

    toMember() {
        wx.navigateTo({
            url: '/pages/mine/members/members?agentInfo=' + JSON.stringify(this.data.agentInfo) + '&userInfo=' + JSON.stringify(this.data.userInfo),
        })
    },

    toStock(e) {
        wx.navigateTo({
            url: `/pages/mine/myStock/myStock?tab=${e.currentTarget.dataset.index}`,
        })
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        let userId = globalData.userInfo.UserId || '';
        console.log(`/pages/index/index?userId=${userId}`, '首页分享链接')
        return {
            title: 'TNTB超多好货等你来看',
            path: `/pages/index/index?userId=${userId}`,
            imageUrl: 'https://tntbeauty.cn/upload/2020082617112274177259.jpg'
        }
    },

    toSpread() {
        wx.navigateTo({
            url: '/pages/mine/spread/spread',
        })
    },
    order_jump(e) {
        console.log(e.currentTarget.dataset.index);
        wx.navigateTo({
            url: `/pages/mine/myOrder/myOrder?index=${e.currentTarget.dataset.index}`,
        })
    },
    toGuide() {
        wx.navigateTo({
            url: '/pages/mine/guide/guide',
        })
    },

    toPages(e) {
        let url = e.currentTarget.dataset.url
        console.log(url)
        wx.navigateTo({
            url: url,
        })
    },
    tixian() {
        wx.navigateTo({
            url: '/pages/mine/withdrawalp/withdrawalp',
        })
    },
    delToken() {
        wx.clearStorage()
        this.setData({
            userInfo: {},
            agentInfo: {},
            phoneCode: 0
        })
    },
    //获取手机号
    getPhoneNumber(e) {
        let that = this
        wx.login({
            success: res => {
                if (res.code) {
                    console.log(e);
                    let obj = {
                        encryptedData: e.detail.encryptedData,
                        iv: e.detail.iv,
                        signature: e.detail.signature,
                        code: res.code
                    }
                    console.log(obj)
                    http.request("POST", "/user/mobile", obj).then((res) => {
                        console.log(res);
                        if (res.data.ErrMsg == "获取成功") {

                            wx.showToast({
                                title: "绑定成功",
                            });
                            wx.hideLoading(),
                                that.setData({
                                    phoneCode: 1,
                                    phoneType: false,
                                    loading: false
                                })
                            wx.setStorageSync('phonecode', that.data.phoneCode)
                        }else{
                            that.setData({
                                phoneCode: 0,
                                phoneType: true
                            })
                            wx.showModal({
                                title: "提示",
                                content: "授权失败"
                            });
                        }
                    })

                }
            }
        });

    },
    eventhandle(){
        console.log("离开",this.data.phoneType);
        if (this.data. phoneCode==1) {
           console.log("正常授权");
        }else{
            this.setData({
                phoneType: false,
                'userInfo.HeadIcon': null,
                loading:false
            })
            wx.clearStorageSync()
        }
    },
  
})